document.addEventListener('DOMContentLoaded', function() {
    // 获取DOM元素
    const userNameInput = document.getElementById('userName');
    const signInBtn = document.getElementById('signInBtn');
    const signInMessage = document.getElementById('signInMessage');
    const signInList = document.getElementById('signInList');
    const activeUsersCount = document.getElementById('activeUsers');
    const totalSignInsCount = document.getElementById('totalSignIns');
    const clearAllBtn = document.getElementById('clearAllBtn');
    const exportExcelBtn = document.getElementById('exportExcelBtn');
    const currentTimeElement = document.getElementById('currentTime');
    const currentDateElement = document.getElementById('currentDate');
    const confirmDialog = document.getElementById('confirmDialog');
    const cancelDelete = document.getElementById('cancelDelete');
    const confirmDelete = document.getElementById('confirmDelete');
    const listViewBtn = document.getElementById('listViewBtn');
    const gridViewBtn = document.getElementById('gridViewBtn');
    
    // 初始化Socket.io连接
    const socket = io();
    
    // 连接状态处理
    socket.on('connect', function() {
        console.log('已连接到服务器');
        showMessage('已连接到服务器', 'success');
        // 启用签到按钮
        if (!hasSignedIn) {
            signInBtn.disabled = false;
        }
    });
    
    socket.on('disconnect', function() {
        console.log('与服务器断开连接');
        showMessage('与服务器断开连接，正在尝试重连...', 'error');
        // 禁用签到按钮
        signInBtn.disabled = true;
    });
    
    socket.on('connect_error', function(error) {
        console.error('连接错误:', error);
        showMessage('连接服务器失败，请检查网络连接', 'error');
    });
    
    // 是否已签到标志
    let hasSignedIn = false;
    // 当前要删除的签到记录ID
    let currentDeleteId = null;
    // 本地存储键名
    const STORAGE_KEY = 'signInSystemData';
    
    // 从本地存储加载数据
    loadDataFromStorage();
    
    // 初始化实时时间
    updateCurrentTime();
    setInterval(updateCurrentTime, 1000);
    
    // 处理在线人数更新
    socket.on('activeUsers', function(count) {
        activeUsersCount.textContent = count;
    });
    
    // 处理现有签到数据
    socket.on('existingSignIns', function(signIns) {
        if (signIns && signIns.length > 0) {
            // 清空列表
            signInList.innerHTML = '';
            
            // 添加所有签到记录
            signIns.forEach(signIn => {
                addSignInToList(signIn);
                
                // 检查当前用户是否已签到
                if (signIn.socketId === socket.id) {
                    hasSignedIn = true;
                    updateUIAfterSignIn();
                }
            });
            
            // 更新签到总人数
            totalSignInsCount.textContent = signIns.length;
            // 更新清空按钮状态
            updateClearButtonState();
            // 更新导出按钮状态
            updateExportButtonState();
            // 保存数据到本地存储
            saveDataToStorage(signIns);
        }
    });
    
    // 处理新的签到记录
    socket.on('newSignIn', function(signIn) {
        // 添加新签到记录到列表
        addSignInToList(signIn);
        
        // 更新签到总人数
        const currentCount = parseInt(totalSignInsCount.textContent);
        totalSignInsCount.textContent = currentCount + 1;
        
        // 更新清空按钮状态
        updateClearButtonState();
        // 更新导出按钮状态
        updateExportButtonState();
        
        // 检查是否是当前用户签到
        if (signIn.socketId === socket.id) {
            hasSignedIn = true;
            updateUIAfterSignIn();
            showMessage('签到成功！', 'success');
        } else {
            // 为其他用户的签到添加动画效果
            const newItem = signInList.firstElementChild;
            if (newItem) {
                newItem.classList.add('new-signin');
                setTimeout(() => {
                    newItem.classList.remove('new-signin');
                }, 2000);
            }
        }
        
        // 获取当前所有签到记录并保存到本地存储
        updateStorageWithCurrentData();
    });
    
    // 处理签到记录删除
    socket.on('signInDeleted', function(signInId) {
        const itemToRemove = document.querySelector(`.signin-item[data-id="${signInId}"]`);
        if (itemToRemove) {
            // 添加删除动画
            itemToRemove.style.height = itemToRemove.offsetHeight + 'px';
            itemToRemove.style.transition = 'all 0.3s ease';
            
            setTimeout(() => {
                itemToRemove.style.height = '0';
                itemToRemove.style.opacity = '0';
                itemToRemove.style.marginBottom = '0';
                itemToRemove.style.padding = '0';
                itemToRemove.style.overflow = 'hidden';
                
                // 更新签到总人数
                const currentCount = parseInt(totalSignInsCount.textContent);
                totalSignInsCount.textContent = currentCount - 1;
                
                // 更新清空按钮状态
                updateClearButtonState();
                // 更新导出按钮状态
                updateExportButtonState();
                
                // 保存更新后的数据到本地存储
                updateStorageWithCurrentData();
                
                setTimeout(() => {
                    itemToRemove.remove();
                    
                    // 检查是否还有签到记录
                    if (signInList.children.length === 0) {
                        const emptyMessage = document.createElement('div');
                        emptyMessage.className = 'empty-message';
                        emptyMessage.innerHTML = `
                            <i class="fas fa-clipboard-list"></i>
                            <p>暂无签到记录</p>
                        `;
                        signInList.appendChild(emptyMessage);
                    }
                }, 300);
            }, 10);
        }
    });
    
    // 处理清空所有记录
    socket.on('allSignInsCleared', function() {
        // 清空列表
        signInList.innerHTML = '';
        
        // 添加空消息
        const emptyMessage = document.createElement('div');
        emptyMessage.className = 'empty-message';
        emptyMessage.innerHTML = `
            <i class="fas fa-clipboard-list"></i>
            <p>暂无签到记录</p>
        `;
        signInList.appendChild(emptyMessage);
        
        // 更新签到总人数
        totalSignInsCount.textContent = 0;
        
        // 更新清空按钮状态
        updateClearButtonState();
        // 更新导出按钮状态
        updateExportButtonState();
        
        // 从本地存储清除数据
        clearDataFromStorage();
        
        showMessage('所有签到记录已清空！', 'success');
    });
    
    // 处理签到状态检查
    socket.on('signInStatus', function(status) {
        console.log('收到签到状态:', status);
        
        if (status.hasSignedIn) {
            hasSignedIn = true;
            updateUIAfterSignIn();
            showSignedInMessage(status.signInRecord);
        } else {
            hasSignedIn = false;
            // 确保签到按钮可用
            signInBtn.disabled = false;
        }
    });
    
    // 处理签到成功
    socket.on('signInSuccess', function(signInRecord) {
        hasSignedIn = true;
        updateUIAfterSignIn();
        showMessage(`签到成功！欢迎 ${signInRecord.name}`, 'success');
    });
    
    // 处理签到错误（重复签到等）
    socket.on('signInError', function(error) {
        console.log('签到错误:', error);
        showMessage(error.message, 'error');
        
        if (error.existingRecord) {
            hasSignedIn = true;
            updateUIAfterSignIn();
            showSignedInMessage(error.existingRecord);
        }
    });
    
    // 处理签到按钮点击
    signInBtn.addEventListener('click', function() {
        handleSignIn();
    });
    
    // 处理回车键提交
    userNameInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            handleSignIn();
        }
    });
    
    // 处理清空所有按钮点击
    clearAllBtn.addEventListener('click', function() {
        if (signInList.children.length > 0) {
            // 显示确认对话框
            confirmDialog.querySelector('p').textContent = '确定要清空所有签到记录吗？';
            currentDeleteId = 'all';
            openDialog();
        }
    });

    // 处理导出Excel按钮点击
    exportExcelBtn.addEventListener('click', function() {
        if (signInList.children.length > 0 && !signInList.querySelector('.empty-message')) {
            // 显示加载状态
            const originalText = exportExcelBtn.innerHTML;
            exportExcelBtn.disabled = true;
            exportExcelBtn.innerHTML = '<span class="loading"></span> 导出中...';
            
            // 发送导出请求
            fetch('/export-excel')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('导出失败');
                    }
                    return response.blob();
                })
                .then(blob => {
                    // 创建下载链接
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.style.display = 'none';
                    a.href = url;
                    
                    // 生成文件名（包含当前日期时间）
                    const now = new Date();
                    const dateStr = now.toLocaleDateString('zh-CN').replace(/\//g, '-');
                    const timeStr = now.toLocaleTimeString('zh-CN', {hour12: false}).replace(/:/g, '-');
                    a.download = `签到记录_${dateStr}_${timeStr}.xlsx`;
                    
                    document.body.appendChild(a);
                    a.click();
                    window.URL.revokeObjectURL(url);
                    document.body.removeChild(a);
                    
                    showMessage('Excel文件导出成功！', 'success');
                })
                .catch(error => {
                    console.error('导出Excel失败:', error);
                    showMessage('导出Excel失败，请重试', 'error');
                })
                .finally(() => {
                    // 恢复按钮状态
                    exportExcelBtn.disabled = false;
                    exportExcelBtn.innerHTML = originalText;
                    updateExportButtonState();
                });
        }
    });
    
    // 处理取消删除
    cancelDelete.addEventListener('click', closeConfirmDialog);
    
    // 处理确认删除
    confirmDelete.addEventListener('click', function() {
        if (currentDeleteId === 'all') {
            // 发送清空所有记录请求到服务器
            socket.emit('clearAllSignIns');
        } else if (currentDeleteId) {
            // 发送删除单个记录请求到服务器
            socket.emit('deleteSignIn', { id: currentDeleteId });
        }
        closeConfirmDialog();
    });
    
    // 签到处理函数
    function handleSignIn() {
        if (hasSignedIn) {
            showMessage('您已经签到过了！', 'error');
            return;
        }
        
        const name = userNameInput.value.trim();
        
        if (!name) {
            showMessage('请输入您的姓名', 'error');
            userNameInput.focus();
            return;
        }
        
        // 验证姓名长度
        if (name.length < 2) {
            showMessage('姓名至少需要2个字符', 'error');
            userNameInput.focus();
            return;
        }
        
        if (name.length > 20) {
            showMessage('姓名不能超过20个字符', 'error');
            userNameInput.focus();
            return;
        }
        
        // 显示加载状态
        const originalText = signInBtn.innerHTML;
        signInBtn.disabled = true;
        signInBtn.innerHTML = '<span class="loading"></span> 签到中...';
        
        // 发送签到信息到服务器
        socket.emit('signIn', { name: name });
        
        // 设置超时处理
        const timeout = setTimeout(() => {
            signInBtn.disabled = false;
            signInBtn.innerHTML = originalText;
            showMessage('签到请求超时，请重试', 'error');
        }, 10000); // 10秒超时
        
        // 监听签到成功事件（一次性）
        socket.once('newSignIn', (signIn) => {
            clearTimeout(timeout);
            if (signIn.socketId === socket.id) {
                signInBtn.innerHTML = '<i class="fas fa-check"></i> 已签到';
                // 不需要重新启用按钮，因为已签到
            }
        });
    }
    
    // 添加签到记录到列表
    function addSignInToList(signIn) {
        // 检查是否已有空消息，如果有则移除
        const emptyMessage = signInList.querySelector('.empty-message');
        if (emptyMessage) {
            signInList.removeChild(emptyMessage);
        }
        
        const signInItem = document.createElement('div');
        signInItem.className = 'signin-item';
        signInItem.setAttribute('data-id', signIn.id);
        
        // 格式化时间
        const formattedTime = new Date(signIn.timestamp).toLocaleTimeString('zh-CN', {
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        });
        
        // 为当前用户的签到记录添加特殊样式
        const isCurrentUser = signIn.socketId === socket.id;
        const itemClass = isCurrentUser ? 'signin-item current-user' : 'signin-item';
        
        signInItem.className = itemClass;
        signInItem.innerHTML = `
            <div class="signin-info">
                <div class="signin-name">
                    <i class="fas fa-user"></i>
                    <span>${signIn.name}</span>
                    ${isCurrentUser ? '<span class="current-user-badge">我</span>' : ''}
                </div>
                <div class="signin-details">
                    <div class="signin-time">
                        <i class="fas fa-clock"></i>
                        <span>${formattedTime}</span>
                    </div>
                    <div class="signin-id">
                        <i class="fas fa-network-wired"></i>
                        <span>${signIn.id}</span>
                    </div>
                </div>
            </div>
            <button class="delete-btn" data-id="${signIn.id}">
                <i class="fas fa-trash-alt"></i>
            </button>
        `;
        
        // 添加到列表最前面
        if (signInList.firstChild) {
            signInList.insertBefore(signInItem, signInList.firstChild);
        } else {
            signInList.appendChild(signInItem);
        }
        
        // 添加删除按钮事件监听
        const deleteBtn = signInItem.querySelector('.delete-btn');
        deleteBtn.addEventListener('click', function() {
            const signInId = this.getAttribute('data-id'); // ID现在是IP地址字符串
            // 显示确认对话框
            confirmDialog.querySelector('p').textContent = '确定要删除这条签到记录吗？';
            currentDeleteId = signInId;
            openDialog();
        });
        
        // 添加动画效果
        setTimeout(() => {
            signInItem.classList.add('fadeIn');
        }, 10);
    }
    
    // 更新签到后的UI
    function updateUIAfterSignIn() {
        signInBtn.disabled = true;
        signInBtn.classList.add('disabled');
        signInBtn.classList.add('signed-in');
        signInBtn.textContent = '已签到';
        userNameInput.disabled = true;
        userNameInput.classList.add('disabled');
        
        // 添加已签到状态提示
        const signedInStatus = document.createElement('div');
        signedInStatus.className = 'signed-in-status';
        signedInStatus.innerHTML = `
            <i class="fas fa-check-circle"></i>
            <span>您已完成签到</span>
        `;
        
        // 检查是否已有状态提示，如果有则替换
        const existingStatus = document.querySelector('.signed-in-status');
        if (existingStatus) {
            existingStatus.replaceWith(signedInStatus);
        } else {
            // 假设签到表单存在
            const signInForm = document.querySelector('.signin-form') || document.body;
            signInForm.appendChild(signedInStatus);
        }
        
        // 为状态提示添加动画效果
        setTimeout(() => {
            signedInStatus.classList.add('slideIn');
        }, 10);
    }
    
    // 显示消息提示
    function showMessage(message, type = 'info') {
        // 使用现有的消息元素
        const messageElement = signInMessage;
        
        // 清除之前的类
        messageElement.className = 'message';
        messageElement.classList.add(type);
        messageElement.textContent = message;
        messageElement.style.display = 'block';
        
        // 添加图标
        let icon = '';
        switch(type) {
            case 'success':
                icon = '<i class="fas fa-check-circle"></i> ';
                break;
            case 'error':
                icon = '<i class="fas fa-exclamation-circle"></i> ';
                break;
            case 'info':
                icon = '<i class="fas fa-info-circle"></i> ';
                break;
        }
        messageElement.innerHTML = icon + message;
        
        // 添加动画效果
        messageElement.style.opacity = '0';
        messageElement.style.transform = 'translateY(-10px)';
        
        setTimeout(() => {
            messageElement.style.opacity = '1';
            messageElement.style.transform = 'translateY(0)';
        }, 10);
        
        // 5秒后自动消失
        setTimeout(() => {
            messageElement.style.opacity = '0';
            messageElement.style.transform = 'translateY(-10px)';
            setTimeout(() => {
                messageElement.style.display = 'none';
            }, 300);
        }, 5000);
    }
    
    // 显示已签到状态的友好提示
    function showSignedInMessage(signInRecord) {
        const messageElement = signInMessage;
        const signInTime = new Date(signInRecord.timestamp).toLocaleString('zh-CN');
        
        messageElement.className = 'message signed-in';
        messageElement.innerHTML = `
            <i class="fas fa-check-circle"></i>
            <div class="signed-in-info">
                <div class="signed-in-title">您已完成签到</div>
                <div class="signed-in-details">
                    <span>姓名：${signInRecord.name}</span>
                    <span>时间：${signInTime}</span>
                    <span>IP：${signInRecord.id}</span>
                </div>
            </div>
        `;
        messageElement.style.display = 'block';
        messageElement.style.opacity = '1';
        messageElement.style.transform = 'translateY(0)';
    }
    
    // 从本地存储加载数据
    function loadDataFromStorage() {
        try {
            const storedData = localStorage.getItem(STORAGE_KEY);
            if (storedData) {
                const parsedData = JSON.parse(storedData);
                
                // 检查数据是否有效且为数组
                if (Array.isArray(parsedData) && parsedData.length > 0) {
                    console.log('从本地存储加载了签到数据');
                    // 注意：这里我们只加载数据但不直接显示，因为服务器会发送数据
                }
            }
        } catch (error) {
            console.error('加载本地存储数据失败:', error);
        }
    }
    
    // 保存数据到本地存储
    function saveDataToStorage(signIns) {
        try {
            localStorage.setItem(STORAGE_KEY, JSON.stringify(signIns));
            console.log('签到数据已保存到本地存储');
        } catch (error) {
            console.error('保存数据到本地存储失败:', error);
        }
    }
    
    // 更新本地存储中的当前数据
    function updateStorageWithCurrentData() {
        try {
            const signInItems = document.querySelectorAll('.signin-item');
            const currentSignIns = [];
            
            signInItems.forEach(item => {
                const id = item.getAttribute('data-id');
                const nameElement = item.querySelector('.signin-name span');
                const timeElement = item.querySelector('.signin-time span');
                
                if (nameElement && timeElement && id) {
                    // 尝试找到对应的socketId（如果在数据中存在）
                    let socketId = null;
                    if (item.classList.contains('current-user')) {
                        socketId = socket.id;
                    }
                    
                    currentSignIns.push({
                        id: id,
                        name: nameElement.textContent,
                        timestamp: new Date().toISOString(), // 使用当前时间作为时间戳
                        socketId: socketId
                    });
                }
            });
            
            if (currentSignIns.length > 0) {
                saveDataToStorage(currentSignIns);
            }
        } catch (error) {
            console.error('更新本地存储数据失败:', error);
        }
    }
    
    // 从本地存储清除数据
    function clearDataFromStorage() {
        try {
            localStorage.removeItem(STORAGE_KEY);
            console.log('本地存储数据已清除');
        } catch (error) {
            console.error('清除本地存储数据失败:', error);
        }
    }
    
    // 打开确认对话框
    function openDialog() {
        UIkit.modal(confirmDialog).show();
    }
    
    // 关闭确认对话框
    function closeConfirmDialog() {
        UIkit.modal(confirmDialog).hide();
        currentDeleteId = null;
    }
    
    // 更新当前时间
    function updateCurrentTime() {
        const now = new Date();
        
        // 格式化日期
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0');
        const day = String(now.getDate()).padStart(2, '0');
        const dateString = `${year}年${month}月${day}日`;
        
        // 格式化时间
        const timeString = now.toLocaleTimeString('zh-CN', {
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        });
        
        // 更新DOM元素
        if (currentDateElement) {
            currentDateElement.textContent = dateString;
        }
        if (currentTimeElement) {
            currentTimeElement.textContent = timeString;
        }
    }
    
    // 更新清空按钮状态
    function updateClearButtonState() {
        const hasSignIns = signInList.children.length > 0 && !signInList.querySelector('.empty-message');
        clearAllBtn.disabled = !hasSignIns;
        if (!hasSignIns) {
            clearAllBtn.classList.add('disabled');
        } else {
            clearAllBtn.classList.remove('disabled');
        }
    }

    // 更新导出按钮状态
    function updateExportButtonState() {
        const hasSignIns = signInList.children.length > 0 && !signInList.querySelector('.empty-message');
        exportExcelBtn.disabled = !hasSignIns;
        if (!hasSignIns) {
            exportExcelBtn.classList.add('disabled');
        } else {
            exportExcelBtn.classList.remove('disabled');
        }
    }
    
    // 补零函数
    function padZero(num) {
        return num < 10 ? '0' + num : num;
    }
    
    // 添加一些简单的动画效果样式
    const style = document.createElement('style');
    style.textContent = `
        .current-user {
            border-left-color: #28a745;
            background-color: #f0f9f4;
        }
        
        .current-user-tag {
            color: #28a745;
            font-size: 14px;
            font-weight: normal;
        }
        
        .signed-in {
            background: #6c757d;
            cursor: not-allowed;
        }
        
        .signed-in:hover {
            transform: none;
            box-shadow: none;
        }
        
        .new-signin {
            animation: pulse 2s ease-in-out;
        }
        
        @keyframes pulse {
            0%, 100% {
                opacity: 1;
                transform: translateX(0);
            }
            50% {
                opacity: 0.8;
                transform: translateX(10px);
            }
        }
    `;
    
    // 将样式添加到页面
    document.head.appendChild(style);
    
    // 视图切换功能
    let currentView = 'list'; // 默认为列表视图
    
    // 切换到列表视图
    function switchToListView() {
        currentView = 'list';
        signInList.className = 'list-view';
        listViewBtn.classList.add('uk-active');
        gridViewBtn.classList.remove('uk-active');
        
        // 重新渲染所有签到项
        refreshSignInList();
    }
    
    // 切换到网格视图
    function switchToGridView() {
        currentView = 'grid';
        signInList.className = 'grid-view';
        gridViewBtn.classList.add('uk-active');
        listViewBtn.classList.remove('uk-active');
        
        // 重新渲染所有签到项
        refreshSignInList();
    }
    
    // 刷新签到列表显示
    function refreshSignInList() {
        // 获取当前所有签到项的数据
        const signInItems = Array.from(signInList.querySelectorAll('.signin-item')).map(item => {
            const nameElement = item.querySelector('.signin-name span');
            const timeElement = item.querySelector('.signin-time span');
            const idElement = item.querySelector('.signin-id span');
            const deleteBtn = item.querySelector('.delete-btn');
            
            return {
                name: nameElement ? nameElement.textContent : '',
                time: timeElement ? timeElement.textContent : '',
                id: idElement ? idElement.textContent : '',
                dataId: deleteBtn ? deleteBtn.getAttribute('data-id') : '',
                isCurrentUser: item.classList.contains('current-user')
            };
        });
        
        // 清空列表
        signInList.innerHTML = '';
        
        // 如果没有签到记录，显示空状态
        if (signInItems.length === 0) {
            const emptyMessage = document.createElement('div');
            emptyMessage.className = 'empty-message uk-text-center uk-text-muted uk-margin-large-top';
            emptyMessage.innerHTML = `
                <span uk-icon="icon: list; ratio: 2" class="uk-display-block uk-margin-small-bottom"></span>
                <p>暂无签到记录</p>
            `;
            signInList.appendChild(emptyMessage);
            return;
        }
        
        // 重新创建签到项
        signInItems.forEach(itemData => {
            const signInItem = document.createElement('div');
            const itemClass = itemData.isCurrentUser ? 'signin-item current-user' : 'signin-item';
            signInItem.className = itemClass;
            signInItem.setAttribute('data-id', itemData.dataId);
            
            signInItem.innerHTML = `
                <div class="signin-info">
                    <div class="signin-name">
                        <i class="fas fa-user"></i>
                        <span>${itemData.name}</span>
                        ${itemData.isCurrentUser ? '<span class="current-user-badge">(我)</span>' : ''}
                    </div>
                    <div class="signin-time">
                        <i class="fas fa-clock"></i>
                        <span>${itemData.time}</span>
                    </div>
                    <div class="signin-id">
                        <i class="fas fa-network-wired"></i>
                        <span>${itemData.id}</span>
                    </div>
                </div>
                <button class="delete-btn" data-id="${itemData.dataId}">
                    <i class="fas fa-trash-alt"></i>
                </button>
            `;
            
            signInList.appendChild(signInItem);
            
            // 重新添加删除按钮事件监听
            const deleteBtn = signInItem.querySelector('.delete-btn');
            deleteBtn.addEventListener('click', function() {
                const signInId = this.getAttribute('data-id'); // ID现在是IP地址字符串
                // 显示确认对话框
                confirmDialog.querySelector('p').textContent = '确定要删除这条签到记录吗？';
                currentDeleteId = signInId;
                openDialog();
            });
        });
    }
    
    // 绑定视图切换按钮事件
    listViewBtn.addEventListener('click', switchToListView);
    gridViewBtn.addEventListener('click', switchToGridView);
    
    // 初始化为列表视图
    switchToListView();
});